package com.example.authority.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.authority.common.Result;

import com.example.authority.entity.Cart;
import com.example.authority.entity.Category;
import com.example.authority.service.CartService;
import com.example.authority.service.CategoryService;
import com.example.authority.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


import com.example.authority.service.GoodsService;
import com.example.authority.entity.Goods;


/**
 * @program: authority-hm-0.0.1
 * @ClassName:GoodsController
 * @description: GoodsController前端控制器
 * @author:dyy
 * @Version 3.0
 **/
@Slf4j
@Tag(name = "商品列表 前端控制器")
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Resource
    private GoodsService goodsService;
    @Resource
    private UserService userService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private CartService cartService;

    /**
     * 新增
     *
     * @param goods
     * @return
     */
    @Operation(summary = "新增")
    @PostMapping
    public Result save(@RequestBody Goods goods) {
        goods.setUsername(userService.getUserInfo().getUsername());

        return Result.success(goodsService.save(goods));
    }

    /**
     * 修改
     *
     * @param goods
     * @return
     */
    @Operation(summary = "修改")
    @PutMapping("/{id}")
    public Result update(@PathVariable Long id, @RequestBody Goods goods) {
        return Result.success(goodsService.updateById(goods));
    }

    /**
     * 查询所有Goods
     *
     * @return
     */
    @Operation(summary = "查询所有Goods")
    @GetMapping
    public Result findAll() {
        return Result.success(goodsService.list());
    }

    /**
     * 获取单个
     *
     * @param id
     * @return
     */
    @Operation(summary = "获取单个")
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(goodsService.getById(id));
    }

    /**
     * 分页显示
     *
     * @param name
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Operation(summary = "分页显示")
    @GetMapping("/page")
    public Result findPage(
            @RequestParam(defaultValue = "") String name,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "") Long cid,
            @RequestParam(defaultValue = "") Integer isShow,
            @RequestParam(defaultValue = "") Integer isRecommand,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (!"".equals(name)) {
            queryWrapper.like("name", name);

        }
        if (cid != null) {
            queryWrapper.eq("cid", cid);
        }
        if (isShow != null) {
            queryWrapper.eq("is_show", isShow);
        }
        if (isRecommand != null) {
            queryWrapper.eq("is_recommand", isRecommand);
        }
        queryWrapper.orderByDesc("id");
        Page<Goods> page = goodsService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<Goods> records = page.getRecords();
        for (Goods goods : records) {
            goods.setCategory(categoryService.getById(goods.getCid()));
        }
        page.setRecords(records);
        return Result.success(page);
    }

    /**
     * 分页显示
     *
     * @param name
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Operation(summary = "首页推荐展示")
    @GetMapping("/home")
    public Result findRecommand(
            @RequestParam(defaultValue = "") String name,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "") Long cid,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        if (cid != null) {
            queryWrapper.eq("cid", cid);
        }
        queryWrapper.eq("is_show", 1L);


        queryWrapper.eq("is_recommand", 1L);

        queryWrapper.orderByDesc("id");
        Page<Goods> page = goodsService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<Goods> records = page.getRecords();
        for (Goods goods : records) {
            goods.setCategory(categoryService.getById(goods.getCid()));
        }
        page.setRecords(records);
        return Result.success(page);
    }

    /**
     * 分页显示
     *
     * @param name
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Operation(summary = "分类页面搜索")
    @GetMapping("/category")
    public Result findCategory(
            @RequestParam(defaultValue = "") String name,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "") Long cid,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }

        queryWrapper.eq("cid", cid);

//        只查询上架的
        queryWrapper.eq("is_show", 1L);


        queryWrapper.orderByDesc("id");
        Page<Goods> page = goodsService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<Goods> records = page.getRecords();
        for (Goods goods : records) {
            goods.setCategory(categoryService.getById(goods.getCid()));
        }
        page.setRecords(records);
        return Result.success(page);
    }

    /**
     * 分页显示
     *
     * @param name
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Operation(summary = "分类页面搜索")
    @GetMapping("/search")
    public Result findSearch(
            @RequestParam(defaultValue = "") String name,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "") Long cid,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }


//        只查询上架的
        queryWrapper.eq("is_show", 1L);
        queryWrapper.orderByDesc("id");
        Page<Goods> page = goodsService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<Goods> records = page.getRecords();
        for (Goods goods : records) {
            goods.setCategory(categoryService.getById(goods.getCid()));
        }
        page.setRecords(records);
        return Result.success(page);
    }

    /**
     * 单个删除
     *
     * @param id
     * @return
     */
    @Operation(summary = "单个删除")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(goodsService.removeById(id));
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Operation(summary = "批量删除")
    @DeleteMapping("/batch/{ids}")
    @Transactional
    public Result deleteByIds(@PathVariable String[] ids) {
        return Result.success(goodsService.removeByIds(Arrays.asList(ids)));
    }

    @Operation(summary = "批量获取")
    @GetMapping("/batch/{ids}")
    @Transactional
    public Result GetByIds(@PathVariable String[] ids) {

//       定义
        List<Goods> goods = new ArrayList<>();
        for (String id : ids) {
            Cart cart = cartService.getById(Long.parseLong(id));
            goods.add(goodsService.getById(cart.getGid()));
        }

        // 5. 返回结果
        return Result.success(goods);
    }

    /**
     * 批量导出
     * 使用的技术为alibaba下面的easyexcel
     * 写数据
     *
     * @param ids
     * @return
     */
    @Operation(summary = "批量导出")
    @GetMapping("/batch/export/{ids}")
    public void exportByIds(@PathVariable String[] ids, HttpServletResponse response) throws IOException {

        List<Goods> list = goodsService.listByIds(Arrays.asList(ids));
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("goods导出数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Goods.class).sheet("sheel1").doWrite(list);

    }

    /**
     * 批量导入
     * 使用的技术为alibaba下面的easyexcel
     * 读数据
     *
     * @param
     */
    @Operation(summary = "批量导入")
    @PostMapping("/batch/upload")
    public Result writeExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Goods.class, new PageReadListener<Goods>(dataList -> {
            dataList.forEach(entity -> goodsService.save(entity.toBuilder().id(null).build()));
        })).sheet().doRead();
        return Result.success();
    }

}